"""
根据页面封装类函数
"""
import time

from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as ec


class BasePage:
    def __init__(self, driver):
        self.driver = driver
        self.wait = WebDriverWait(driver, 10)

    def get_msg(self):
        """获取message信息并返回"""
        msg = WebDriverWait(self.driver, 10).until(
            lambda d: d.find_element("xpath", """//p[@class="prompt-msg"]""").text
        )
        return msg

    def close_msg(self):
        """获取系统提示，然后关闭"""
        msg = self.get_msg()
        el_close = ("xpath", '//button[@class="am-close"]')
        self.driver.find_element(*el_close).click()
        time.sleep(1)
        return msg

    def click_by_js(self, element):
        """JS强制点击"""
        self.driver.execute_script("arguments[0].click();", element)


class UserAddressIndex(BasePage):
    """
    用户收货地址页面
    http://116.62.63.211/shop/useraddress/index.html
    """
    el_new_address = ("xpath", '//button[@data-popup-title="新增地址"]')

    def new_address(self):
        """创建新的收获地址"""
        el = self.driver.find_element(*self.el_new_address)
        el.click()
        iframe = self.driver.find_element("xpath", '//iframe[starts-with(@src, "http://")]')
        self.driver.switch_to.frame(iframe)  # 切到iframe页面
        return UserAddressSave(self.driver)

    def edit_address_by_alias(self, alias):
        """通过别名编辑"""
        el = self.driver.find_element("xpath", f'//span[text()="{alias}"]/../../../div[2]//a[text()=" 编辑"]')
        el.click()
        iframe = self.driver.find_element("xpath", '//iframe[starts-with(@src, "http://")]')
        self.driver.switch_to.frame(iframe)
        return UserAddressEdit(self.driver)

    def del_address_by_alias(self, alias):
        """通过别名删除"""
        del_el = self.driver.find_element("xpath", f'//span[text()="{alias}"]/../../../div[2]//a[text()=" 删除"]')
        self.click_by_js(del_el)
        try:
            # 等待元素可点击并重新定位
            confirm_button = WebDriverWait(self.driver, 10).until(
                ec.element_to_be_clickable(("xpath", '//span[@class="am-modal-btn"][text()="确定"]'))
            )
            # 点击元素
            confirm_button.click()
            print("删除成功")
        except Exception as e:
            print(f"点击元素失败: {e}", "删除失败")
        return self.get_msg()

    def del_address_all(self):
        """删除全部地址"""
        self.driver.refresh()
        address_list = self.driver.find_elements("xpath", '//a[text()=" 删除"]')
        for i in address_list:
            time.sleep(0.5)
            self.click_by_js(i)
            try:
                # 等待元素可点击并重新定位
                confirm_button = WebDriverWait(self.driver, 10).until(
                    ec.element_to_be_clickable(("xpath", '//span[@class="am-modal-btn"][text()="确定"]'))
                )
                # 点击元素
                confirm_button.click()
                print("删除成功")
            except Exception as e:
                print(f"点击元素失败: {e}", "删除失败")
            self.get_msg()
        return


class UserAddressSave(BasePage):
    """
    用户新增地址页面
    http://116.62.63.211/shop/useraddress/saveinfo.html
    """
    el_alisa = ("xpath", '//input[@name="alias"]')
    el_name = ("xpath", '//input[@name="name"]')
    el_tel = ("xpath", '//input[@name="tel"]')

    el_province = ("xpath", '//span[text()="省份"]')
    el_province_option = ("xpath", f'//li[text()="江西省"]')
    el_city = ("xpath", '//span[text()="城市"]')
    el_city_option = ("xpath", f'//li[text()="赣州市"]')
    el_county = ("xpath", '//span[text()="区/县"]')
    el_county_option = ("xpath", f'//li[text()="章贡区"]')

    el_address = ("xpath", '//*[@id="form-address"]')
    el_default = ("xpath", '/html/body/div[1]/form/div[6]/div')
    el_submit = ("xpath", '//button[text()="保存"]')

    def input(self, alias, name, tel, province, city, county, address, default=False):
        """输入交互"""
        self.driver.find_element(*self.el_alisa).send_keys(alias)
        self.driver.find_element(*self.el_name).send_keys(name)
        self.driver.find_element(*self.el_tel).send_keys(tel)

        self.driver.find_element(*self.el_province).click()
        self.driver.find_element(*self.el_province_option).click()
        self.driver.find_element(*self.el_city).click()
        self.driver.find_element(*self.el_city_option).click()
        self.driver.find_element(*self.el_county).click()
        self.driver.find_element(*self.el_county_option).click()

        self.driver.find_element(*self.el_address).send_keys(address)
        if default:
            self.driver.find_element(*self.el_default).click()

    def submit(self):
        """点击保存交互"""
        self.driver.find_element(*self.el_submit).click()
        return self.get_msg()  # 返回message信息


class UserAddressEdit(UserAddressSave):
    """
    用户编辑地址页面
    http://116.62.63.211/shop/useraddress/saveinfo/id/44540.html
    """

    def input(self, alias=None, name=None, tel=None, province=None, city=None, county=None, address=None, default=None):
        if alias:
            self.driver.find_element(*self.el_alisa).clear()
            self.close_msg()
            self.driver.find_element(*self.el_alisa).send_keys(alias)
        if name:
            self.driver.find_element(*self.el_name).clear()
            self.close_msg()
            self.driver.find_element(*self.el_name).send_keys(name)
        if tel:
            self.driver.find_element(*self.el_tel).clear()
            self.close_msg()
            self.driver.find_element(*self.el_tel).send_keys(tel)
        if province:
            self.driver.find_element(*self.el_province).click()
            self.driver.find_element(*self.el_province_option).click()
        if city:
            self.driver.find_element(*self.el_city).click()
            self.driver.find_element(*self.el_city_option).click()
        if county:
            self.driver.find_element(*self.el_county).click()
            self.driver.find_element(*self.el_county_option).click()
        if address:
            self.driver.find_element(*self.el_address).clear()
            self.close_msg()
            self.driver.find_element(*self.el_address).send_keys(address)
        if default:
            self.driver.find_element(*self.el_default).click()

    def submit(self):
        """点击保存交互"""
        self.driver.find_element(*self.el_submit).click()
        return self.get_msg()  # 返回message信息


class LoginBasePage(BasePage):
    """
    登录页面
    """
    user_input_xpath = ("xpath", '//input[@name="accounts"]')
    password_input_xpath = ("xpath", '//input[@name="pwd"]')
    login_button_xpath = ("xpath", '//button[text()="登录"]')

    def login(self, username="15970794846", password="15970794846."):
        """输入账号密码，默认账号密码都是正确的"""
        self.driver.find_element(*self.user_input_xpath).send_keys(username)
        self.driver.find_element(*self.password_input_xpath).send_keys(password)
        self.driver.find_element(*self.login_button_xpath).click()
        msg = self.get_msg()
        return msg


class PersonalDataPage(BasePage):
    """
    个人资料页面
    http://116.62.63.211/shop/personal/index.html
    """
    head_img_xpath = ("xpath", '//dt[text()="头像"]/../dd/img')
    head_update_xpath = ("xpath", '//dt[text()="头像"]/../dd[1]/span/a[text()="修改"]')
    head_input_xpath = ("xpath", '//input[@type="file"]')
    upload_input_xpath = ("xpath", '//button[text()="确认上传"]')

    def head_update(self,
                    a_new_img=r"C:\Users\29266\Desktop\测试学习\码尚教育-软件测试\python自动化学习\wbe_test_object\data\baidu.png"):
        """上传头像"""
        self.driver.find_element(*self.head_update_xpath).click()
        self.driver.find_element(*self.head_input_xpath).send_keys(a_new_img)
        time.sleep(1)
        self.driver.find_element(*self.upload_input_xpath).click()
        msg = self.get_msg()
        return msg

    def save_head(self):
        """保存头像地址"""
        value = self.driver.find_element(*self.head_img_xpath).get_attribute('src')
        return value
